<template>
  <div class="inner-container">
    <el-row :gutter="30">
      <el-col :span="16">
        <div style="display:flex;justify-content:space-between;flex-wrap:wrap">
          <div>
            <el-icon :size="14"><Monitor/></el-icon>
            <span style="margin-left:5px">数据统计</span>
          </div>
        </div>

        <el-row :gutter="10" style="font-size:12px">
          <!-- 订单客户 -->
          <el-col :span="8">
            <el-card shadow="never">
              <div style="margin-bottom:20px">
                <el-icon :size="14"><Avatar/></el-icon>
                <span style="margin-left:5px">订单客户</span>
              </div>
              <el-row style="margin-bottom:10px;text-align:center">
                <el-col :span="8">今日</el-col>
                <el-col :span="8">本周</el-col>
                <el-col :span="8">本月</el-col>
              </el-row>
              <el-row style="margin-bottom:25px;text-align:center">
                <el-col :span="8">{{ orderStats.today }}</el-col>
                <el-col :span="8">{{ orderStats.week }}</el-col>
                <el-col :span="8">{{ orderStats.month }}</el-col>
              </el-row>
              <el-row>
                <el-col :span="14">
                  <div id="chart01" style="width:120px;height:120px"></div>
                </el-col>
                <el-col :span="10" style="padding-left:10px">
                  <p style="font-size:10px;color:#999">本月目标订单</p>
                  <p>{{ orderStats.orderIndex }}</p>
                  <p style="font-size:10px;color:#999">本月实际订单</p>
                  <p>{{ orderStats.month }}</p>
                </el-col>
              </el-row>
            </el-card>
          </el-col>
          <!-- 到店客户 -->
          <el-col :span="8">
            <el-card shadow="never">
              <div style="margin-bottom:20px">
                <el-icon :size="14"><User/></el-icon>
                <span style="margin-left:5px">到店客户</span>
              </div>
              <el-row style="margin-bottom:10px;text-align:center">
                <el-col :span="8">今日</el-col>
                <el-col :span="8">本周</el-col>
                <el-col :span="8">本月</el-col>
              </el-row>
              <el-row style="margin-bottom:25px;text-align:center">
                <el-col :span="8">{{visitStats.today}}</el-col>
                <el-col :span="8">{{visitStats.week}}</el-col>
                <el-col :span="8">{{visitStats.month}}</el-col>
              </el-row>
              <el-row>
                <el-col :span="14">
                  <div id="chart02" style="width:120px;height:120px;"></div>
                </el-col>
                <el-col :span="10" style="padding-left:10px">
                  <p style="font-size:10px;color:#999">本月目标到店客户</p>
                  <p>{{visitStats.userIndex}}</p>
                  <p style="font-size:10px;color:#999">本月实际到店客户</p>
                  <p>{{visitStats.month}}</p>
                </el-col>
              </el-row>
            </el-card>
          </el-col>
          <!-- 合并产值（元） -->
          <el-col :span="8">
            <el-card shadow="never">
              <div style="margin-bottom:20px">
                <el-icon :size="14"><Money/></el-icon>
                <span style="margin-left:5px">合并产值（元）</span>
              </div>
              <el-row style="margin-bottom:10px;text-align:center">
                <el-col :span="8">今日</el-col>
                <el-col :span="8">本周</el-col>
                <el-col :span="8">本月</el-col>
              </el-row>
              <el-row style="margin-bottom:25px;text-align:center">
                <el-col :span="8">{{ productionStats.today }}</el-col>
                <el-col :span="8">{{ productionStats.week }}</el-col>
                <el-col :span="8">{{ productionStats.month }}</el-col>
              </el-row>
              <el-row>
                <el-col :span="14">
                  <div id="chart03" style="width:120px;height:120px;"></div>
                </el-col>
                <el-col :span="10" style="padding-left:10px">
                  <p style="font-size:10px;color:#999">本月目标产值</p>
                  <p>{{toFixed2(productionStats.costIndex)}}</p>
                  <p style="font-size:10px;color:#999">本月实际产值</p>
                  <p>{{productionStats.month}}</p>
                </el-col>
              </el-row>
            </el-card>
          </el-col>
        </el-row>

        <br>
        <div style="display:flex;justify-content:space-between">
          <div>
            <el-icon :size="14"><Files/></el-icon>
            <span style="margin-left:5px">任务列表</span>
          </div>
        </div>

        <br>
        <el-table :data="taskList" v-loading="loading" size="small" class="custom-table">
          <el-table-column prop="userId" label="编号" align="center"></el-table-column>
          <el-table-column prop="updateTime" label="时间" align="center"></el-table-column>
          <el-table-column prop="transferProgress" label="任务类型" :formatter="taskTypeFormatter" min-width="120" show-overflow-tooltip></el-table-column>
          <el-table-column prop="overview" label="任务概述" min-width="240" show-overflow-tooltip></el-table-column>
          <el-table-column prop="designerProgress" label="处理状态" :formatter="orderStatusFormatter" align="center">
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template #default="scope">
              <el-button
                  type="primary"
                  link
                  @click="gotoOrderDetail(scope.row.orderId)"
              >
                查看
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
      <!-- ./左侧 -->

      <el-col :span="8" style="border-left:1px solid #ddd">
        <div style="display:flex;justify-content:space-between;flex-wrap:wrap">
          <div>
            <el-icon :size="14"><DataAnalysis/></el-icon>
            <span style="margin:0 15px 0 5px">本月排行榜</span>
          </div>
        </div>

        <el-table :data="rankList" size="small" class="custom-table">
          <el-table-column prop="ranking" label="排名" align="center">
            <template #default="scope">
              <img v-if="scope.row.ranking===1" src="~@/assets/images/rank_no1.png" style="width:15px;vertical-align:middle">
              <img v-if="scope.row.ranking===2" src="~@/assets/images/rank_no2.png" style="width:13px;vertical-align:middle">
              <img v-if="scope.row.ranking===3" src="~@/assets/images/rank_no3.png" style="width:11px;vertical-align:middle">
              <span v-if="scope.row.ranking > 3">{{ scope.row.ranking }}</span>
            </template>
          </el-table-column>
          <el-table-column
              prop="manager"
              label="客户经理"
              align="center"
          ></el-table-column>
          <el-table-column prop="cost" label="合并产值 / 元" align="center">
            <template #default="scope">
              {{ formatValue(scope.row.cost) }}
            </template>
          </el-table-column>
        </el-table>
      </el-col>
      <!-- ./右侧 -->
    </el-row>
  </div>
</template>

<script setup>
import {onMounted, ref} from 'vue'
import * as echarts from 'echarts'
import request from "@/utils/request";
import router  from "@/router"
const loading = ref(false)

const orderStats=ref({ today:0, week:0, month:0, orderIndex:0 })//订单卡片
const visitStats= ref({ today:undefined, week:undefined, month:undefined, userIndex:undefined })//到店客户卡片
const productionStats=ref({ today:0, week:0, month:0, costIndex:0})//产值卡片
let a = orderStats.value.month/orderStats.value.orderIndex


const orderStatsData = () => {
  loading.value = true
  request.get('/api/dashboard/orderStats/select', {
  }).then(res => {
    orderStats.value = res.data[0]
    console.log(res.data)

    initChart('chart01', 1, '#5ca5f4')
  })
  console.log(a);
}

const visitStatsData = () => {
  loading.value = true
  request.get('/api/dashboard/visitStats/select', {
  }).then(res => {
    visitStats.value=res.data[0]

    initChart('chart02', 2, '#fcbf4c')
  })
}

const productionStatsData = () => {
  loading.value = true
  request.get('/api/dashboard/productionStats/select', {
  }).then(res => {
    productionStats.value=res.data


    initChart('chart03', 3, '#f96364')
  })
}

const toFixed2 = (a) => {
  return a.toFixed(2)
}




/*orderStats visitStats  productionStats */
/*---------------------------------------------------------------------------------------------------------------------*/
// 初始化图表
const initChart = (selector, type, color) => {
  let complete = 0;
  if (type === 1) {
    complete = orderStats.value.month / (orderStats.value.orderIndex || 0.001);
  } else if (type === 2) {
    complete = visitStats.value.month / (visitStats.value.userIndex || 0.001);
  } else if (type === 3) {
    complete = productionStats.value.month / (productionStats.value.costIndex||0.001);
  }
  complete *= 100;
  // 基于准备好的dom，初始化echarts实例
  let chart = echarts.init(document.getElementById(selector))
  // 指定图表的配置项和数据
  let option = {
    title: [
      {text: '完成度', left: 'center', top: '35%', textStyle: {fontSize: 10, color: '#999'}},
      {text: `${complete.toFixed(2)}%`, left: 'center', top: '50%', textStyle: {fontSize: 10, color: '#999'}}
    ],
    series: [{
        name: '完成度',
        type: 'pie',
        radius: ['70%', '90%'],
        center: ['50%', '50%'],
        startAngle: 0,
        color: [color, '#f2f2f2'],
        emphasis: {scale: false},
        labelLine: {show: false},
        data: [
          {value: complete, name: ''},
          {value: (100 - complete), name: '', emphasis: {label: {show: false}}}
        ]
      }]
  }
  // 使用刚指定的配置项和数据显示图表。
  chart.setOption(option);
  // 当窗口大小变化时重置chart的大小
  window.onresize = () => {
    chart.resize()
  }
}


//----------------------------------------------------------------------------------------------------------------------------------------
const taskList = ref([{
}])
// 跳转到订单详情页
const gotoOrderDetail = (orderId) => {
  router.push({
    path: '/crm/orderDetail',
    query: { id: orderId }
  })
}

const taskListData = () => {
  loading.value = true
  request.get('/api/dashboard/taskList/select', {
  }).then(res => {
    taskList.value = res.data
    taskList.value = res.data.map(item => ({
      userId: item.userId,       // 客户编号（假设接口返回 clientId）
      updateTime: item.updateTime, // 订单更新时间
      transferProgress: item.transferProgress,
      overview: `${item.orderNumber}-${item.name}-${item.propertyName}`, // 拼接订单编号-客户姓名-楼盘名称
      designerProgress: item.designerProgress === null ? 0 : item.designerProgress,// 处理状态，为空时默认待处理
      orderId: item.orderId,       // 订单ID（用于跳转）
    }));
    loading.value=false;
  })
}



const rankList = ref([{}])
// 格式化金额
const formatValue = (value) => {
  return new Intl.NumberFormat('zh-CN', { style: 'decimal' }).format(value)
}
const rankListData = () => {
  loading.value = true
  request.get('/api/dashboard/rank/select', {
  }).then(res => {
    rankList.value = res.data.map((item, index) => ({
      ranking: index + 1,
      manager: item.manager,
      cost: item.cost
    }))
  })
}



/*------------------------------------字典-----------------------------------------------------------------------------------*/
const taskTypeArr = ref([]);
const  taskTypeFormatter = (row,column,cellValue,index)=> {
  if (!taskTypeArr.value) {
    return cellValue;
  }
  for (let item of taskTypeArr.value) {
    if (item.value == cellValue) {
      cellValue = item.label;
    }
  }
  return cellValue;
}
  const orderStatusArr = ref([]);
  const orderStatusFormatter = (row, column, cellValue, index) => {
    if (!orderStatusArr.value) {
      return cellValue;
    }
    for (let item of orderStatusArr.value) {
      if (item.value == cellValue) {
        cellValue = item.label;
      }
    }
    return cellValue;
  }
  /*-----------------------------------------------------------------------------------------------------------------------*/

  onMounted(() => {
    orderStatsData()
    visitStatsData()
    productionStatsData()
    loadDictOptions(taskTypeArr, 'customer_status');
    loadDictOptions(orderStatusArr, 'order_status');
    taskListData()
    rankListData()
    // initChart('chart01', 1, '#5ca5f4')
    // initChart('chart02', 2, '#fcbf4c')
    // initChart('chart03', 3, '#f96364')
  })
</script>

<style scoped>
.custom-table >>> .el-table__row > td {
  border: none;
}

.custom-table >>> .el-table__inner-wrapper::before {
  height: 0;
}
</style>
